package com.ohc.笔试;

import java.util.*;

public class TestDemo {

    public static String weightRandom(Map<String, Integer> map) {
        //获取map里的key值集合
        Set<String> keySet = map.keySet();
        List<String> weights = new ArrayList<>();
        for (Iterator<String> it = keySet.iterator(); it.hasNext(); ) {
            //循环获取map里key值
            String weightStr = it.next();
            //获取key对应的value值，即每个金额对应的次数
            int weight = map.get(weightStr);
            for (int i = 0; i < weight; i++) {
                //等于将90个'10元',9个'100元',1个'1000元'分别添加到weights集合中
                weights.add(weightStr);
            }
        }
        //抽奖时随机获取集合里（100个金额字符串集）的字符串的下标
        int idx = new Random().nextInt(weights.size());
        //返回对应的金额
        return weights.get(idx);

    }

//测试方法如下

    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        //往map里添加的value值90,9,1代表着各自金额抽中的概率
        map.put("10元", 90);
        map.put("100元", 9);
        map.put("1000元", 1);

       /* //抽一次奖，看抽出金额是多少
        System.out.println(weightRandom(map));*/

        //抽奖100次，看不同奖金分别出现多少次
        for (int i = 0; i < 100; i++) {
            System.out.println(weightRandom(map));
        }
    }

}
